package com.sky.controller.admin;
import com.sky.constant.MessageConstant;
import com.sky.result.Result;
import com.sky.utils.AliOssUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.util.UUID;

/**
 * @Description TODO
 * @Author itheima
 * @Date 2023-07-11 11:44
 */
@RestController
@Slf4j
@RequestMapping("/admin/common")
@Api(tags = "文件上传接口")
public class CommonController {
    @Autowired
    private AliOssUtil aliOssUtil;
    @ApiOperation("文件上传")
    @PostMapping("/upload")
    public Result<String> upload(MultipartFile file){
            log.info("文件上传:{}",file);
            //获取原始文件名
        try {
            String originalFilename = file.getOriginalFilename();
            //截取文件名后缀 lastIndexOf(String str) 返回指定子字符串最后一次出现的字符串中的索引。
            // substring(int beginIndex) 返回一个字符串，该字符串是此字符串的子字符串。就是以指定索引,切割得到索引后面的字符串
            String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
            //构造新字符串UUID.randomUUID().toString()的作用是生成全局唯一的一个字符串
            //构造新的文件名称
            String s = UUID.randomUUID().toString() + substring;
            //文件的请求路径
            String upload = aliOssUtil.upload(file.getBytes(), s);
            return Result.success(upload);
        } catch (Exception e) {
            log.error("文件上传失败:{}",e);
            //throw new BaseException(MessageConstant.UPLOAD_FAILED);
        }
                return  Result.error(MessageConstant.UPLOAD_FAILED);
    }
}
